import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
//import java.util.Calendar;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.sound.sampled.DataLine.Info;

public class PlayAudioThread extends Thread {

	FileInputStream waveStream;
	AudioInputStream audioInputStream = null;
	AudioFormat audioFormat;
	Info info;
	SourceDataLine dataLine = null;

	final int buffer_size_bytes = 10*1024; 
	
	static long last_time = 0;
	
	public PlayAudioThread(String in_wav_file, int vid_fps) throws UnsupportedAudioFileException, IOException, LineUnavailableException {
    	try {
    		waveStream = new FileInputStream(in_wav_file);
    	} catch (FileNotFoundException e) {
    	    e.printStackTrace();
    	    return;
    	}
   	
   	    audioInputStream = AudioSystem.getAudioInputStream(this.waveStream);

    	// Obtain the information about the AudioInputStream
    	audioFormat = audioInputStream.getFormat();
    	info = new Info(SourceDataLine.class, audioFormat);
    	
    	// opens the audio channel
	    dataLine = (SourceDataLine) AudioSystem.getLine(info);
	    dataLine.open(audioFormat, (buffer_size_bytes));

    	// Starts the music :P
    	dataLine.start();
	}


	@Override
	public void run() {

		int readBytes = 0;
		byte[] audioBuffer = new byte[buffer_size_bytes];
		

		do
		{
			long delta = Global.cur_vid_time - Global.cur_aud_time;
			//System.out.println("AV diff: " + delta);
			
			if(delta < Global.lower_threshold)
			{
				//Thread.yield();
				//continue;
			}

			try {

			readBytes = audioInputStream.read(audioBuffer, 0,
					audioBuffer.length);
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			while(Global.pause==1)
			{
				Global.cur_aud_time=Global.paused_aud_time;
				dataLine.stop();
			}
			//System.out.println("\t\t aud ms:" + dataLine.getMicrosecondPosition());
			dataLine.start();
			
			if (readBytes >= 0){
			    dataLine.write(audioBuffer, 0, readBytes);
			}	
			
			Global.cur_aud_time = dataLine.getMicrosecondPosition();
			
			//long now = Calendar.getInstance().getTimeInMillis();
			
			System.out.println("audio "+Global.cur_aud_time );
			
		} while (readBytes >= 0);
	}

}
